/**
 * 
 */
package demo.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Collection;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

/**
 * @author Roger Xu
 * 
 */
public class FileIOUtils {

    /**
     * Opens a {@link FileOutputStream} for the specified file.
     * 
     * @param fileName
     * @param append
     * @return
     * @throws IOException
     * @see {@link FileUtils#openOutputStream(File)}
     */
    public static OutputStream openOutputStream(final String fileName, boolean append) throws IOException {
        checkFile(fileName);
        return new FileOutputStream(fileName, append);
    }

    /**
     * Opens a {@link PrintWriter} for the specified file.
     * 
     * @param fileName
     * @param encoding
     * @return
     * @throws IOException
     * @see {@link FileUtils#openOutputStream(File)}
     */
    public static Writer openWriter(final String fileName, final String encoding) throws IOException {
        checkFile(fileName);
        return new PrintWriter(fileName, encoding);
    }

    public static void writeLines(final Collection<String> lines, final Writer writer) throws IOException {
        IOUtils.writeLines(lines, IOUtils.LINE_SEPARATOR, writer);
    }

    public static void writeLine(final String line, final Writer writer) throws IOException {
        writer.append(line).append(IOUtils.LINE_SEPARATOR);
    }

    public static void close(final Writer writer) {
        IOUtils.closeQuietly(writer);
    }

    private static void checkFile(final String fileName) throws IOException {
        final File file = new File(fileName);

        if (file.exists()) {
            if (file.isDirectory()) {
                throw new IOException("File '" + file + "' exists but is a directory");
            }
            if (file.canWrite() == false) {
                throw new IOException("File '" + file + "' cannot be written to");
            }
        } else {
            File parent = file.getParentFile();
            if (parent != null && parent.exists() == false) {
                if (parent.mkdirs() == false) {
                    throw new IOException("File '" + file + "' could not be created");
                }
            }
        }
    }

}
